package com.xingshentech.ugv.operate.module.httpdata

import com.xingshentech.utils.SecurityUtil
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

class DecryptionInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        // 获取原始的响应
        var request = chain.request()
        //这里wait 到响应后再处理返回的数据
        val originalResponse = chain.proceed(request)

        if (!originalResponse.isSuccessful) {
            return originalResponse
        }

        val responseBody = originalResponse.body()
        if (responseBody != null) {
            //body string 只能读取一次
            val resBodyStr = responseBody.string()
            try {
                var decryptedData: String? = null
                decryptedData =
                    String(SecurityUtil.gmSm4CbcDecryptData(resBodyStr.toByteArray(), true))
//                XsLog.e("reponseUrl=${request.url().url()}", decryptedData)
                val decryptedBody = ResponseBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    decryptedData
                )
                return originalResponse.newBuilder().body(decryptedBody).build()
            } catch (e: Exception) {
                e.printStackTrace()
                val body = ResponseBody.create(responseBody.contentType(), resBodyStr)
                return originalResponse.newBuilder().body(body).build()
            }
        }
        return originalResponse
    }
}